<?php


class QuestionService extends Service
{
  /**
   * @param string $className
   * @return QuestionService
   */
  public static function instance($className = __CLASS__)
  {
    return parent::instance($className);
  }

  /**
   * 获取题目列表
   * @param int $pageSize 分页大小
   * @param int $bank_id 题库编号
   * @param bool $with 关联
   * @param string $keywords 关键词
   * @return array
   */
  public function getList($pageSize = 20, $bank_id = 0, $with = true, $keywords = '')
  {
    $criteria = new CDbCriteria();
    $criteria->condition = 'bank_id=:bank_id';
    $criteria->params = array(':bank_id' => $bank_id);
    //关键字
    if (!empty($keywords)) {
      $criteria->addSearchCondition('title', $keywords);
    }
    //关联
    if ($with) {
      $criteria->with = array(
          'bank'
      );
    }
    $criteria->order = 'question.question_id desc';
    $count = Question::model()->count($criteria);
    $pages = new CPagination($count);
    $pages->pageSize = $pageSize;
    $pages->applyLimit($criteria);
    $criteria->offset = $pages->currentPage * $pages->pageSize;
    $list = Question::model()->findAll($criteria);
    return array(
        'list' => $list,
        'pages' => $pages
    );
  }

  /**
   * 添加/编辑题目
   * @param array $data 题目数据
   * @param int $user_id 创建者ID(编辑时凭证)
   * @return array|bool|string
   */
  public function post($data = array(), $user_id = 0)
  {
    if (empty($data['question_id'])) {
      $question = new Question();
    } else {
      $question = Question::model()->with('bank')->findByPk($data['question_id']);
      if ($question->bank->user_id != $user_id) {
        return '对不起，该题目所属题库不是你创建的!';
      }
    }
    $question->attributes = $data;
    return $question->save() ? true : $question->errors;
  }

  /**
   * 删除题目
   * @param array $list
   * @return array|bool
   */
  public function delete($list = array())
  {
    $criteria = new CDbCriteria();
    $criteria->addInCondition('question_id',$list);
    return Question::model()->deleteAll($criteria)?true:false;
  }
} 